package com.firesrc.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.util.StringUtil;

/**
 * Servlet implementation class MailType
 */
public class MailType extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private final List<String> list = new ArrayList<String>();

  /**
   * @see HttpServlet#HttpServlet()
   */
  public MailType() {
    super();
    list.add("163.com");
    list.add("163.cn");
    list.add("163.net");
    list.add("139.com");
    list.add("263.net");
    list.add("126.com");
    list.add("gmail.com");
    list.add("sohu.com");
    list.add("qq.com");
    list.add("sina.com");
    list.add("sina.cn");
    list.add("hotmail.com");
    list.add("21cn.com");
    list.add("yahoo.cn");
    list.add("yahoo.com");
    list.add("yahoo.com.cn");
    list.add("tom.com");
    list.add("yeah.net");

    // TODO Auto-generated constructor stub
  }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String mailString = request.getParameter("mailString");
    Map<String, StringBuilder> mapFromMailString = getMapFromMailString(mailString);
    request.setAttribute("map", mapFromMailString);
    request.getRequestDispatcher("/mailtype.jsp").forward(request, response);

  }

  public Map<String, StringBuilder> getMapFromMailString(String mails) {
    String[] splitc = StringUtil.splitc(mails, ';');
    Map<String, StringBuilder> allMap = new HashMap<String, StringBuilder>();
    for (String string : splitc) {
      int indexOf = string.indexOf("@");
      if (indexOf > 0) {
        string = string.toLowerCase();
        String mailType = string.substring(indexOf + 1, string.length());

        mailType = getRealMailTypeName(mailType);
        StringBuilder mailString = allMap.get(mailType);
        if (mailString != null) {
          mailString.append(',').append(string);
        } else {
          StringBuilder builder = new StringBuilder(string);
          allMap.put(mailType, builder);
        }
      }
    }
    return allMap;
  }

  private String getRealMailTypeName(String string) {
    if (list.contains(string)) {
      return string;
    } else {
      return "综合类";
    }
  }
}
